#!/usr/bin/env bash

check_file_exists () {

    if [ ! -f $1 ]; then

        echo "Invalid $2: $3 is not a valid directory"
        exit 1

    fi

}

add_system_property_arg () {

    if [ ! -z "$2" ]; then
        ALLURE_ARGS+="\"-D$1=$2\" "
    fi

}

add_allure_cp () {

    if [ ! -z "$1" ]; then
        ALLURE_CP+=":$1"
    fi

}

# start
# find jre or jdk and test it

if [ ! -z "$JRE_HOME" ]; then

    export JAVA=${JRE_HOME}/bin/java
    check_file_exists "$JAVA" "JRE_HOME" "$JRE_HOME"

elif [ ! -z "$JAVA_HOME" ]; then

    export JAVA=${JAVA_HOME}/bin/java
    check_file_exists "$JAVA" "JAVA_HOME" "$JAVA_HOME"

else
    # find java in PATH
    export JAVA="java"
fi

eval "${JAVA} -version" 2>/dev/null

export RETCODE=$?

if [ $RETCODE -ne 0 ]; then

    echo "Could not find java implementation: try to set JAVA_HOME, JRE_HOME or add java to PATH"
    exit 1

fi

# find and validate allure home directory

if [ -z "$ALLURE_HOME" ]; then

    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do
        DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
        SOURCE="$(readlink "$SOURCE")"
        [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
    done
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    ALLURE_HOME="`cd "$DIR/..";pwd`"

fi

check_file_exists "$ALLURE_HOME/bin/allure" "ALLURE_HOME" "$ALLURE_HOME"

ALLURE_ARGS=""
ALLURE_CP="$ALLURE_HOME/lib/*"
ALLURE_MAIN="ru.yandex.qatools.allure.CommandLine"

add_system_property_arg "allure.home" "${ALLURE_HOME}"
add_system_property_arg "allure.config" "${ALLURE_CONFIG}"
add_system_property_arg "allure.bundle.javaOpts" "${ALLURE_BUNDLE_JAVA_OPTS}"
add_allure_cp "$ALLURE_HOME/conf"

ALLURE_COMMAND="${JAVA} ${JAVA_ARGS} -cp \"${ALLURE_CP}\" ${ALLURE_ARGS} ${ALLURE_MAIN} $@"

eval ${ALLURE_COMMAND}